import Vue from 'vue'
import Vuex from 'vuex'
import fetch from '@/utils/request'

Vue.use(Vuex)
// vuex实现数据持久化存储
// 插件，可以监听每次用户提交给mutaion(所有的数据最终都会经过mutaion)
const myPlugin = (store) => {
  // 当 store 初始化后调用
  store.subscribe((mutation, state) => {
    console.log('mutation:', mutation)
    localStorage.setItem('token', state.token)
    localStorage.setItem('cartList', JSON.stringify(state.cartList))
    // 每次 mutation 之后调用
    // mutation 的格式为 { type, payload }
  })
}

// vuex可以存储数据，放置不同页面的逻辑，统一管理
export default new Vuex.Store({
  state: {
    token: localStorage.getItem('token') || '', // 存储token数据
    list: [],
    total: 0,
    cartList: JSON.parse(localStorage.getItem('cartList')) || [], // 购物车数据
  },
  plugins: [myPlugin],
  // 计算属性
  getters: {
    // 总价
    allPrice(state) {
      return state.cartList.reduce((num, item) => {
        return num + item.count * item.price
      }, 0)
    },
  },
  // 处理一切逻辑
  mutations: {
    set_token(state, token) {
      state.token = token
    },
    set_list(state, data) {
      state.list = data.list
      state.total = data.total
    },
    // 加入购物车逻辑 home
    toCart(state, item) {
      // 去重
      const goods = state.cartList.find((v) => v.id === item.id)
      if (goods) {
        goods.count++
      } else {
        item.count = 1
        state.cartList.push(item)
      }
    },

    // ++ about
    addItem(state, item) {
      item.count++
    },

    // -- about
    reduceItem(state, item) {
      if (item.count <= 1) {
        if (window.confirm('确定删除吗?')) {
          state.cartList.splice(
            state.cartList.findIndex((v) => v.id === item.id),
            1
          )
        }
        return
      }
      item.count--
    },
  },
  // 处理异步
  actions: {
    async fetch_list({ commit }, { page = 1, size = 10 }) {
      const response = await fetch.get('/api/list', { params: { page, size } })
      console.log('response:', response)
      commit('set_list', response.data)
    },
  },
  modules: {},
})
